package com.example.hw;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.app.Instrumentation.ActivityResult;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.NumberPicker;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.NumberPicker;


public class ActOrder extends Activity {
	
	Map<Integer, Button> drinkButtons;			//自製產生飲料按鈕
	Map<Integer,OnClickListener> drinkListen;	//飲料按鈕自製事件
	Map <Integer,String[]>userChooseDrink;		//使用者選到哪些飲料
	String[][] drinksData;						//全部的飲料
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.actorder);
		InitialComponet();
	}
	
	TableLayout orderDetail 		= null;
	LinearLayout drinkBtnList 		= null;
	Button btnDrinkList 			= null;
	Button btnSendOrder				= null;
	Button btnClear					= null;
	private void InitialComponet() {
		btnDrinkList = (Button)findViewById(R.id.btnBackToMain);
		btnDrinkList.setOnClickListener(btn_goBackToMain);
		//主頁面表單
		orderDetail = (TableLayout)findViewById(R.id.orderDetail);
		drinkBtnList = (LinearLayout)findViewById(R.id.drinkBtnList);
		
		//增加選單按鈕
		addDrinkBtn();
		
		btnSendOrder = (Button)findViewById(R.id.btnSendOrder);
		btnSendOrder.setOnClickListener(btn_SendOrder);
		
		btnClear = (Button)findViewById(R.id.btnClear);
		btnClear.setOnClickListener(btn_Clear);
	}
	
	OnClickListener btn_goBackToMain = new OnClickListener() {
		public void onClick(View v) {
			goFinish();
		}
	};
		
	
	//要寫入資料庫
	OnClickListener btn_SendOrder = new OnClickListener() {
		public void onClick(View v) {
			ShopFactory sf = new ShopFactory();
			sf.goInsertOrders(ActOrder.this);
			
			String[] orders = sf.goQueryOrders(ActOrder.this);	//要給訂單的ID
			System.out.println("單號="+orders[0]);
			
			int check = orderDetail.getChildCount();
			int usrCheckNum  = 0;	//確認寫入有要寫入飲料清單,給orderDetail_id
			
			for(int i = 0 ; i< check ;i++){
				TableRow tempRow = (TableRow) orderDetail.getChildAt(i);
				String ck = ((TextView)tempRow.getChildAt(4)).getText().toString();
				//確認是否有點餐
				if(Integer.parseInt(ck)==0){
					orderDetail.removeViewAt(i);
					check -=1;
				}
				if(check==0){
					return;
				}
			}
			
			for(int i = 0 ; i< check ;i++){
				usrCheckNum +=1;
			}
			
			int order_id = Integer.parseInt(orders[0]);
			int[] prodcut_ids = new int[usrCheckNum]; 
			String[] drinknames = new String[usrCheckNum];//給drinkName
			int[] prices = new int[usrCheckNum];	  //給price
			int[] numbers = new int[usrCheckNum] ;
			
			for(int i = 0 ; i< check ;i++){
				TableRow tempRow = (TableRow) orderDetail.getChildAt(i);
				String drinkname = ((TextView)tempRow.getChildAt(1)).getText().toString();
				String price = ((TextView)tempRow.getChildAt(2)).getText().toString();
				String num = ((TextView)tempRow.getChildAt(4)).getText().toString();
				String product_id = sf.goQueryProducts(ActOrder.this, drinkname)[0];
				prodcut_ids[i] = Integer.parseInt(product_id);
				drinknames[i] = drinkname; 
				prices[i] = Integer.parseInt(price);
				numbers[i] = Integer.parseInt(num);
			}
			
			for(int i = 0 ; i < usrCheckNum ; i++){
				sf.goInsertOrderDetail(ActOrder.this, i+1, //項次要從1開始	
						order_id,prodcut_ids[i], numbers[i], prices[i]);
			}
			
			String[][] result = sf.goQueryOrder(ActOrder.this, order_id);
			for(int i = 0 ; i < result.length ; i++){
				System.out.print("項次"+result[i][0]+" ");
				System.out.print("訂單號碼"+result[i][1]+" ");
				System.out.print("產品號碼"+result[i][2]+" ");
				System.out.print("數量"+result[i][3]+" ");
				System.out.println("單價" +result[i][4]+" ");
			}
			//訂單結束，清除
			orderDetail.removeAllViews();
			goFinish();
		}
	};
	
	protected void goFinish() {
		//返回上一個Class
		ActOrder.this.finish();
		Intent intent = new Intent(this, ActMain_Hw.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
	}
	
	OnClickListener btn_Clear = new OnClickListener() {
		public void onClick(View v) {
			//清除訂單
			orderDetail.removeAllViews();
		}
	};
	
	
	
	public void addDrinkBtn() {
		ShopFactory sf = new ShopFactory();
		drinksData = sf.goQueryProducts(ActOrder.this);
		
		drinkButtons = new HashMap<Integer, Button>();
		drinkListen	= new HashMap<Integer,OnClickListener>();
		OnClickListener btn_drink[] = new OnClickListener[drinksData.length];
		
		for(int i = 0 ; i < drinksData.length ; i ++){
			
			setDrinkBtn(i,drinksData[i][1],drinksData[i][2],btn_drink[i]);	
		
			LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, 
					LayoutParams.WRAP_CONTENT,1.0f);

			drinkButtons.get(i).setOnClickListener(drinkListen.get(i));
			drinkBtnList.addView(drinkButtons.get(i),lp);
		}
		drinkBtnList.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, 
					LayoutParams.WRAP_CONTENT));
		//drinkBtnList.setOrientation(1);
	}
	

	public void setDrinkBtn(int i,String name,String price,OnClickListener even){
		Button b = new Button(this);
		b.setText(name+"\n"+price);
		drinkButtons.put(i, b);
		final int key = i;
		drinkListen.put(i,even = new OnClickListener() {			
			@Override
			public void onClick(View v) {
				setOrderTableRow(key);
			}
		});
	}
	//設定那一列的資料
	public void setOrderTableRow(int key) {
		//初始
		userChooseDrink = new HashMap<Integer, String[]>();
		
		ShopFactory sf = new ShopFactory();
		//Key + 1,是因為表上是從0開始
		String[] selectDrink = sf.goQueryProducts(ActOrder.this,key+1);
		//之後比較好寫入資料
		userChooseDrink.put(key,selectDrink);
		
		//重覆確認
		boolean check = checkDrink(selectDrink[1]);
		if(check == false){
			System.out.println("重覆");
			return;
		}
		
		orderDetail.setStretchAllColumns(true);
		int colCount = selectDrink.length; 
		int rowCount = orderDetail.getChildCount();
		
		TableRow tr = new TableRow(this);
		Object rows[] = new Object[colCount-1];
		Object nums[] = new Object[colCount-1];	
		
		rows = myRow(rows,rowCount,selectDrink[1],selectDrink[2]);

		
		for(int i = 0 ; i < colCount-1 ; i++){
			tr.addView((TextView)rows[i]);
		}
		//自製數字選擇
		myNumberPicker myNum = new myNumberPicker(this, orderDetail);
		nums = myNum.returnMyNumberPicker();
		
		tr.addView((Button)nums[0],50,100);
		tr.addView((TextView)nums[1]);
		tr.addView((Button)nums[2],50,100);
		
		orderDetail.addView(tr, new TableLayout.LayoutParams
				(TableLayout.LayoutParams.WRAP_CONTENT,
				 TableLayout.LayoutParams.WRAP_CONTENT));
		
	}
	//確認是否有重覆點選的飲料
	private boolean checkDrink(String drinkName) {
		int rows = orderDetail.getChildCount();

		for (int i = 0; i < rows; i++) {
			TableRow tempRow = (TableRow) orderDetail.getChildAt(i);
			String ck = ((TextView)tempRow.getChildAt(1)).getText().toString();
			if(ck.equals(drinkName)){
				return false;					
			}
		}
		return true;
	}
	//拿取飲料資料庫裡的資料
	public Object[] myRow(Object[] rows,int rowCount,String drinkName, String price){
		
		rows[0] = new TextView(this);			//項目
		rows[1] = new TextView(this);			//飲料名稱
		rows[2] = new TextView(this);			//單價
		
		for(int i = 0 ; i < rows.length ; i++){
			((TextView) rows[i]).setLayoutParams(new TableRow.LayoutParams
					(100,TableRow.LayoutParams.WRAP_CONTENT,1.0f));
		}
		
		if(rowCount==0){
			((TextView) rows[0]).setText(Integer.toString(1));
		}
		if(rowCount>0){
			((TextView) rows[0]).setText(Integer.toString(rowCount+1));
		}
		((TextView) rows[1]).setText(drinkName);
		((TextView) rows[2]).setText(price);
		
		return rows;
	}

}

class myNumberPicker{
	Object np[] = new Object[3];
	
	public myNumberPicker(ActOrder actOrder,TableLayout orderDetail){

		np[0] = new Button(actOrder);
		np[1] = new TextView(actOrder);
		np[2] = new Button(actOrder);
		
		((Button) np[0]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));
		
		((TextView) np[1]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));
		
		((Button) np[2]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));

		((Button) np[0]).setText("-");
		((TextView) np[1]).setText(Integer.toString(0));
		((Button) np[2]).setText("+");
		
		((Button) np[0]).setTextSize(16);
		((TextView) np[1]).setTextSize(16);
		((Button) np[2]).setTextSize(16);
		
		((Button) np[0]).setOnClickListener(btn_div);
		((Button) np[2]).setOnClickListener(btn_plus);
	}
	
	public myNumberPicker(ActDrink actDrink){

		np[0] = new Button(actDrink);
		np[1] = new TextView(actDrink);
		np[2] = new Button(actDrink);
		
		((Button) np[0]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));
		
		((TextView) np[1]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));
		
		((Button) np[2]).setLayoutParams(new TableRow.LayoutParams
				(50,TableLayout.LayoutParams.WRAP_CONTENT,1.0f));

		((Button) np[0]).setText("-");
		((TextView) np[1]).setText(Integer.toString(0));
		((Button) np[2]).setText("+");
		
		((Button) np[0]).setTextSize(16);
		((TextView) np[1]).setTextSize(16);
		((Button) np[2]).setTextSize(16);
		
		((Button) np[0]).setOnClickListener(btn_div);
		((Button) np[2]).setOnClickListener(btn_plus);
	}
	
	public Object[] returnMyNumberPicker() {
		return np;
	}
	OnClickListener btn_div = new OnClickListener() {
		public void onClick(View v) {
			int tempNum = Integer.parseInt(((TextView) np[1]).getText().toString());
			if(tempNum!=0){
				tempNum -=1;
				((TextView) np[1]).setText(Integer.toString(tempNum));
			}else{
				((TextView) np[1]).setText(Integer.toString(0));
			}
			System.out.println(((TextView) np[1]).getText().toString());
		}
	};
	OnClickListener btn_plus = new OnClickListener() {
		public void onClick(View v) {
			int tempNum = Integer.parseInt(((TextView) np[1]).getText().toString());
			if(tempNum>=0){
				tempNum +=1;
				((TextView) np[1]).setText(Integer.toString(tempNum));
			}
			System.out.println(((TextView) np[1]).getText().toString());
		}
	};
}